/*
 * Copyright 2011 CraneLeeon authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.crane.webtemplate.dao.security;


import java.sql.SQLException;
import java.util.List;
import org.crane.webtemplate.dao.BaseDAO;
import org.crane.webtemplate.dao.HibernateUtil;
import org.crane.webtemplate.model.BO;
import org.crane.webtemplate.model.security.User;
import org.hibernate.Query;

/**
 *
 * @author CraneLeeon
 */
public class UserDAO extends BaseDAO{
    private static final Class BOCLASS= User.class;

    @Override
    public String getBOName() {
        return BOCLASS.getName();
    }

    @Override
    public String getBOSimpleName() {
        return BOCLASS.getSimpleName();
    }

    @Override
    public void delete(Long id) throws SQLException {
        User user = (User) this.get(id);
        if(!user.getId().equals(Long.valueOf(1)))super.delete(id);
    }

    @Override
    public void delete(BO bo) throws SQLException {
        User user = (User) bo;
        if(!user.getId().equals(Long.valueOf(1)))super.delete(bo);
    }

    public BO getUserByName(String code) throws SQLException {
        Query qy = HibernateUtil.getCurrentSession().createQuery(
                    ("from "+this.getBOName()+" as $ where $.name = (?)").replaceAll("\\$", this.getBOName().replaceAll("\\.", "_"))
                    );
        qy.setParameter(0, code);
        List<BO> bos =  qy.list();
        if(bos != null && bos.size()>0){
            return bos.get(0);
        }else{
            return null;
        }
    }

}
